<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="searchMap.username" placeholder="用户名" style="width: 200px" class="filter-item" @keyup.enter.native="fetchData" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="fetchData">
        搜索
      </el-button>
      <el-button v-waves class="filter-item create" type="success" icon="el-icon-circle-plus-outline" @click="handleCreate()">
        添加用户
      </el-button>
    </div>

    <el-table v-loading="listLoading" border fit stripe highlight-current-row :data="list" style="width: 100%" height="500" max-height="500" size="small">
      <el-table-column sortable label="序号" prop="id" width="70" align="center">
        <template slot-scope="{ row }">
          <p>{{ row.id }}</p>
        </template>
      </el-table-column>

      <!-- 列表头像：绑定 row.image -->
      <el-table-column label="头像" width="120" align="center">
        <template slot-scope="{ row }">
          <el-image :src="row.image" :fit="contain" />
          <el-image :src="row.image" :fit="contain" />
        </template>
      </el-table-column>

      <el-table-column label="联系人" prop="name" align="center" />

      <el-table-column label="用户名" prop="username" align="center" />

      <el-table-column label="电话" prop="phone" align="center" />

      <el-table-column label="邮箱" width="200" align="center">
        <template slot-scope="{ row }">
          <p>{{ row.email }}</p>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="220">
        <template slot-scope="{ row, $index }">
          <el-button size="mini" type="warning" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleDelete(row, $index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination v-show="total > 0" :current-page="searchMap.page" background :page-sizes="[5, 10, 20]" :page-size="searchMap.limit" layout="sizes, total, prev, pager, next,jumper" :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="pojo" label-position="left" label-width="70px" style="width: 85%; margin-left: 50px">
        <el-row :gutter="20" align="middle">
          <el-col :span="24">
            <el-form-item label="头像">
              <el-upload class="avatar-uploader" action="/api/image/upload" name="image" :show-file-list="false" :headers="headers" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                <!-- 弹窗头像：绑定 pojo.image -->
                <img v-if="pojo.image" :src="pojo.image" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon" />
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="姓 名">
              <el-input v-model="pojo.name" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="用户名">
              <el-input v-model="pojo.username" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系方式">
              <el-input v-model="pojo.phone" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="邮 箱">
              <el-input v-model="pojo.email" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="角 色">
              <template>
                <el-checkbox-group v-model="roleIds">
                  <el-checkbox v-for="r in roles" :key="r.id" :value="r.id" :label="r.id">{{ r.name }}</el-checkbox>
                </el-checkbox-group>
              </template>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false"> 取消 </el-button>
        <el-button type="primary" @click="dialogStatus === 'create' ? createData() : updateData()">
          提交
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import admin from '@/api/admin' 
import admin from '@/api/admin' 
import role from '@/api/role'
import { getToken } from '@/utils/auth'
export default {
  data() {
    return {
      headers: {
        token: getToken()
      },
      brands: null,
      hotels: null,
      roles: null,
      roleIds: [1, 2, 3],
      list: null,
      total: 0,
      listLoading: true,
      searchMap: {
        page: 1,
        limit: 5,
        username: undefined
      },
      dialogFormVisible: false,
      dialogStatus: '',
      rules: {
        title: [
          {
            required: true,
            message: 'title is required',
            trigger: 'blur'
          }
        ]
      },
      // 与后端字段一致，用 image 存储头像路径
      pojo: {
        id: undefined,
        image: '', 
        username: '',
        name: '',
        phone: '',
        email: '',
        roleIds: []
      },
      textMap: {
        update: '编辑用户',
        create: '创建用户'
      }
    }
  },
  created() {
    this.fetchData(),
    this.fetchRoles()
  },
  methods: {
    handleDelete(row, index) {
      this.$confirm('确定要删除这条记录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        admin.delete(row.id).then((res) => {
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 3000
          })
          this.list.splice(index, 1)
          if (res.code === 0) {
            this.fetchData()
          }
        })
      })
        .catch(() => {
          this.$notify({
            title: '提示',
            message: '取消删除',
            type: 'info',
            duration: 3000
          })
        })
    },
    fetchData() {
      this.listLoading = true
      admin.getList(this.searchMap).then((res) => {
        this.listLoading = false
        this.list = res.data
        this.total = res.count
      })
    },
    fetchRoles() {
      this.listLoading = true
      role.getAll().then((res) => {
        this.listLoading = false
        this.roles = res.data
      })
    },
    handleSizeChange(limit) {
      this.searchMap.limit = limit
      this.fetchData()
    },
    handleCurrentChange(page) {
      this.searchMap.page = page
      this.fetchData()
    },
    handleConditionChange(condition) {
      this.searchMap.username = condition
      this.fetchData()
    },
    fetchCurrentUserRoleIds(id) {
      role.getRoleList(id).then(res => {
        this.roleIds = res.data
      })
    },
    handleUpdate(row) {
      this.fetchCurrentUserRoleIds(row.id)
      this.roleIds = []
      // 复制 row 数据（包含 image 字段）
      this.pojo = Object.assign({}, row) 
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleCreate() {
      this.resetPojo()
      this.roleIds = []
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
    },
    updateData() {
      this.pojo.roleIds = this.roleIds
      admin.update(this.pojo).then(res => {
        if (res.code === 0) {
          this.$notify({
            title: '成功',
            message: '修改成功',
            type: 'success',
            duration: 3000
          })
          this.fetchData()
          this.dialogFormVisible = false
        }
      })
    },
    createData() {
      this.pojo.roleIds = this.roleIds
      admin.add(this.pojo).then(res => {
        if (res.code === 0) {
          this.$notify({
            title: '成功',
            message: '添加成功',
            type: 'success',
            duration: 3000
          })
          this.fetchData()
          this.dialogFormVisible = false
        }
      })
    },
    // 上传成功后，将路径赋值给 pojo.image
    handleAvatarSuccess(res) {
      console.log('头像上传成功，路径：', res.data)
      this.pojo.image = res.data 
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$notify({
          title: '错误',
          message: '上传头像图片只能是 JPG 或 PNG 格式!',
          type: 'error',
          duration: 3000
        })
      }
      if (!isLt2M) {
        this.$notify({
          title: '错误',
          message: '上传头像图片大小不能超过 2MB!',
          type: 'error',
          duration: 3000
        })
      }
      return isJPG && isLt2M
    },
    resetPojo() {
      this.pojo = {
        id: undefined,
        image: '', 
        username: '',
        name: '',
        phone: '',
        email: '',
        roleIds: []
      }
    }
  }
}
</script>

<style>
.filter-item {
  margin-bottom: 10px;
  margin-right: 10px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
.app-container {
  padding: 0%;
}
.create {
  float: right;
  margin-right: 0%;
}
</style>